<template>
  <lay-card>
    <lay-form :model="ruleDict" ref="ruleFormRef" :rules="rulesInfo" required>
      <lay-row space="10" v-if="mode === 'add'">
        <lay-col md="2"></lay-col>
        <lay-col md="4">
          <lay-dropdown updateAtScroll ref="manualRefMenu" :clickOutsideToClose="false" :clickToClose="false">
            <lay-button size="sm">
              <lay-icon type="layui-icon-add-one" size="sm" style="width: 8%"></lay-icon>复制规则
            </lay-button>
            <template #content>
              <lay-dropdown-menu>
                <RulesTree
                  :showCheckbox="false"
                  @insertRule="queryTargetRuleDetail"
                  @cancelAction="cancelSelect"
                ></RulesTree>
              </lay-dropdown-menu>
            </template>
          </lay-dropdown>
        </lay-col>
      </lay-row>
      <lay-row space="1">
        <lay-col>
          <lay-quote>
            <lay-col md="20"><p>基础信息</p></lay-col>
          </lay-quote>
        </lay-col>
      </lay-row>
      <lay-row space="1">
        <lay-col md="1"></lay-col>
        <lay-col md="7">
          <lay-form-item label="规则编号：" mode="inline">
            <lay-input
                size="sm"
                placeholder="自动生成"
                v-model="ruleDict.function_id"
                disabled></lay-input>
          </lay-form-item>
        </lay-col>
        <lay-col md="7">
          <lay-form-item label="规则名称：" prop="function_name" mode="inline">
            <lay-input
                size="sm"
                v-model="ruleDict.function_name"
                :disabled="disable"
            ></lay-input>
          </lay-form-item>
        </lay-col>
        <lay-col md="7">
          <lay-form-item label="规则描述：" mode="inline">
            <lay-input size="sm" v-model="ruleDict.description" :disabled="disable"></lay-input>
          </lay-form-item>
        </lay-col>
      </lay-row>
      <lay-row space="1">
        <lay-col md="1"></lay-col>
        <lay-col md="7">
          <lay-form-item label="规则分类：" prop="classify" mode="inline">
            <lay-dropdown updateAtScroll>
              <lay-input size="sm" placeholder="请选择或输入" :disabled="disable" v-model="ruleDict.classify"></lay-input>
              <template #content>
                  <lay-dropdown-menu>
                    <lay-dropdown-menu-item v-for="item in classes" @click="ruleDict.classify = item">
                      {{ item }}
                    </lay-dropdown-menu-item>
                  </lay-dropdown-menu>
              </template>
            </lay-dropdown>
          </lay-form-item>
        </lay-col>
        <lay-col md="7">
          <lay-form-item label="是否公共：" prop="is_publish" mode="inline">
            <lay-switch size="sm" v-model="ruleDict.is_publish" :disabled="disable"></lay-switch>
          </lay-form-item>
        </lay-col>
        <lay-col md="7">
          <lay-form-item label="英文标识：" mode="inline">
            <lay-input size="sm" placeholder="用于绑定数据库字段" :disabled="disable" v-model="ruleDict.identity" disable></lay-input>
          </lay-form-item>
        </lay-col>
      </lay-row>
      <lay-row space="1">
        <lay-col><lay-quote>规则详情</lay-quote></lay-col>
      </lay-row>
      <lay-row space="10" v-if="ruleDict.parameter">
        <lay-col md="1"></lay-col>
        <lay-col md="2">
          <h4 style="margin-top: 10px;float: right;margin-right: 10px">参数：</h4>
        </lay-col>
        <lay-col md="20">
          <lay-row>
            <lay-col md="12" v-for="item in ruleDict.parameter">
              <lay-input
                  v-model="item.value"
                  :placeholder="item.description"
                  style="width: 80%;margin-bottom: 10px"
              >
                <template #prepend>{{item.name}}:</template>
              </lay-input>
            </lay-col>
          </lay-row>
        </lay-col>
      </lay-row>
      <RuleDescription
          :mode="modeRule"
          v-if="ruleDict.content !== null && reloadContent"
          :describe_mode="ruleDict.describe_mode"
          :content="ruleDict.content"
          @setRuleContent="updateContent"
          ref="ruleDescRef"
          :disabled="disable"
      ></RuleDescription>
      <lay-row space="10" v-if="!disable">
        <lay-col md="6"></lay-col>
        <lay-col md="4">
            <lay-button type="normal" @click="addRuleForm">{{ submitButton }}</lay-button>
        </lay-col>
        <lay-col md="14">
            <p id="error_message" :style="msg_style">{{display_result}}</p>
        </lay-col>
      </lay-row>
    </lay-form>
  </lay-card>
</template>

<script lang="ts">
import RuleDescription from "./RuleDescription.vue";
import RulesTree from "./RulesTree.vue";

export default {
  name: "AddRule",
  components: {
    RuleDescription,
    RulesTree
  }
}
</script>

<script lang="ts" setup>
import {onBeforeMount, onMounted, reactive, ref} from "vue";
import {layer} from "@layui/layer-vue";
import {addRuleApi, modifyRuleApi, queryRuleClassApi, queryRuleDetailApi} from "../../api/module/rule";
import {nanoid} from "nanoid";
import {notify} from "../../untils/tip";

const modeRule = ref('rule');
const classes = ref([]);
const display_result = ref('');
const msg_style = ref('color: green');
const copyFlag = ref(false);
const reloadContent = ref(true);
const manualRefMenu = ref();
const ruleFormRef = ref();
const rulesInfo = ref({
  function_name : {
    type : 'string',
    min: 1,
    max: 50
  },
  is_publish : {
    type : 'boolean'
  },
  classify : {
    type : 'string'
  }
});

const ruleDict: any = ref({
  function_id: '',
  function_name: '',
  description: '',
  example: '',
  classify: '',
  is_publish: false,
  describe_mode: 5,
  identity: '',  // 要映射或匹配的数据库字段名称
  content: null
});

// 初始的规则描述信息
const ruleRawContent = reactive({
  ruleParams: [], // 正则表达式，枚举值，SQL，规则固化，条件表达式
  leftParams: [], // 判断表达式，左侧的值
  midParams: [],  // 判断表达式，中间的判断符号
  rightParams: [] // 判断表达式，右侧的值
});

const {mode, node} = defineProps({
  mode: {type: String, default: ref('add')},
  node: {type: Object, default: ref({})}
});

// 定义与 ref 同名变量
const ruleDescRef = ref <any> ();
const submitButton = ref('提交');
const disable = ref(false);

onBeforeMount(()=>{
  queryRuleDetail();
  getRulesClasses();
});

// 刷新 content 数据
const updateContent = (data: any) => {
  ruleDict.value.content = data.content;
  ruleDict.value.describe_mode = data.describe_mode;
};

const cancelSelect = () => {
  manualRefMenu.value.hide();
};

const queryTargetRuleDetail = async (function_id: string) => {
  const {result, status, message} = await queryRuleDetailApi({function_id: function_id});
  if(status === 'success'){
    reloadContent.value = false;
    ruleDict.value = result;
    ruleDict.value.function_id = '';
    ruleDict.value.function_name = result.function_name + '_' + nanoid().substring(0,4);
    ruleDict.value.describe_mode = result.describe_mode;
    ruleDict.value.classify = result.classify;
    ruleDict.value.is_publish = result.is_publish;
    ruleDict.value.identity = result.identity;
    if(result.content === null){
      ruleDict.value.content = ruleRawContent;
    }else {
      ruleDict.value.content = result.content;
    }
    ruleDescRef.value.setContent(result.describe_mode, result.content);
    copyFlag.value = false;
    cancelSelect();
    reloadContent.value = true;
  }else {
    layer.msg(message);
  }
};

const judgeResult = (status: string, message: string) => {
    display_result.value = message;
    if(status === 'success'){
      msg_style.value = 'color: green';
    }else {
      msg_style.value = 'color: red';
    }
    notify(status, message);
};

// 查询规则详情
const queryRuleDetail = async () => {
  if(mode !== 'add'){
    const {result, status, message} = await getRulesDetail(node.function_id);
    if(status === 'success'){
      ruleDict.value = result;
    }else {
      layer.msg(message);
    }
  }
  // 设置按钮状态
  if(mode === 'modify'){
    submitButton.value = '更新';
    disable.value = false;
  }else if(mode === 'copy'){
    submitButton.value = '复制';
    disable.value = false;
  }else if(mode === 'add'){
    submitButton.value = '新增';
    disable.value = false;
    ruleDict.value.content = ruleRawContent;
    ruleDict.value.describe_mode = 5;
  }else {
    // mode = 'query' 查看规则，不允许任何修改，只读
    disable.value = true;
  }
};

// 新增，更新规则
const addRuleForm = async () => {
  let tempData = ruleDescRef.value.submitContent();
  if(tempData.content.defaultRule === ''){
    notify('fail', '添加规则为空，请新增后再添加！')
  }else {
    updateContent(tempData);
    console.log('addRuleForm : ', ruleDict.value);
    if(mode === 'add' || mode === 'copy'){
      ruleDict.value.function_id = '';
      let {result, status, message} = await addRuleApi(ruleDict.value);
      judgeResult(status, message);
    }else if(mode === 'modify'){
      let {result, status, message} = await modifyRuleApi(ruleDict.value);
      judgeResult(status, message);
    }else{
      let {result, status, message} = reactive({result: [], status: 'failed', message: '不支持的操作类型！'})
      judgeResult(status, message);
    }
  }
};

const getRulesClasses = async () => {
  let {result, status, message} = await queryRuleClassApi();
  if(status === 'success'){
    classes.value = result;
  }
};

const getRulesDetail = async (rule_id: any) => {
  let ruleResult: any = await queryRuleDetailApi({function_id: rule_id});
  return ruleResult;
};


</script>

<style scoped>

</style>